package com.clover.ehcache.service.impl;

import com.clover.ehcache.domain.UserVO;
import com.clover.ehcache.repository.UserRepository;
import com.clover.ehcache.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {

    //单引号不能少，否则会报错，被识别是一个对象
    private static final String CACHE_KEY = "'userInfo'";
    private static final String CACHE_NAME = "user";

    @Autowired
    private UserRepository userRepository;

    //@CacheEvict(value = CACHE_NAME,key = CACHE_KEY)
    @CachePut( value = CACHE_NAME , key = "'userInfo_'+#user.id")
    @Override
    public UserVO save(UserVO user) {
        log.info("保存用户信息");
        return userRepository.save(user);
    }

    @Cacheable( value = CACHE_NAME , key = "'userInfo_'+#id")
    @Override
    public Optional<UserVO> findById(Long id) {
        log.error("查询用户信息，没走缓存");
        return userRepository.findById(id);
    }

    @CachePut( value = CACHE_NAME , key = "'userInfo_'+#user.id")
    @Override
    public UserVO update(UserVO user) throws Exception{
        Optional<UserVO> userOptional = userRepository.findById(user.getId());
        if( !userOptional.isPresent()){
            log.error("系统异常，当前用户不存在");
            throw  new Exception("没有找到用户信息");
        }
        userOptional.get().setUsername(user.getUsername());
        userOptional.get().setEmail(user.getEmail());
        return userRepository.save(userOptional.get());
    }

    //主要用于数据新增和修改操作上
    @CacheEvict( key = "'userInfo_'+#id",value = CACHE_NAME)
    @Override
    public void delete(Long id){
        log.info("删除用户信息");
        userRepository.deleteById(id);
    }
    @Cacheable( key = "'users'" , value = CACHE_NAME)
    @Override
    public List<UserVO> findAll(){
        return (List<UserVO>) userRepository.findAll();
    }
}
